<template>
  <el-dialog v-model="rejectOrderDialogVisible" title="拒单" width="30%">
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="原因" prop="reason">
        <el-input required="required" placeholder="需要说明原因..." v-model="form.reason" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="rejectOrderDialogVisible = false">取消操作</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, getCurrentInstance, watch } from 'vue'
import ComponentHat from '@/plugins/type'
import { FormRules, FormValidateCallback } from 'element-plus'
import { ShopRejectOrderParam } from '@/types/param/order'
const { $store, $API, $modal } = <ComponentHat>getCurrentInstance().proxy
const formRef = ref()
// 表单规则
const rules = reactive<FormRules>({
  reason: [
    {
      required: true,
      message: '原因不能为空',
      trigger: 'blur'
    },
    {
      trigger: ['blur', 'change'],
      pattern: /.{2,}/,
      message: '至少2个字符'
    }
  ]
})
const emits = defineEmits<{
  (e: 'rejected'): void
}>()
// 用户拒单对话框可见性控制
const rejectOrderDialogVisible = ref(false)
function getDefaultForm(): ShopRejectOrderParam {
  return {
    orderId: undefined,
    reason: ''
  }
}
const form = ref(getDefaultForm())
// 确认
function confirm() {
  formRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      const result = await $API.order.shopRejectOrder(form.value)
      if (result.success) {
        rejectOrderDialogVisible.value = false
        emits('rejected')
      } else {
        $modal.msgError(result.message)
      }
    }
  })
}
// 监听隐藏，当隐藏时清理掉orderId
watch(
  () => rejectOrderDialogVisible.value,
  (newVal) => {
    if (newVal === false) {
      form.value = getDefaultForm()
    }
  }
)
// 调起
function callOut(_orderId: number) {
  if (_orderId == null) $modal.msgError('出现异常,无效的订单id')
  rejectOrderDialogVisible.value = true
  form.value.orderId = _orderId
}
defineExpose({
  callOut
})
</script>

<style scoped></style>
